import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUser, getMmyPermissions } from '@/api/user'
import router from '@/router'
import { resetRouter } from '@/router/index'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    menus: [],
    points: []
  },
  mutations: {
    setToken(state, token) {
      setToken(token)
      state.token = token
    },
    setUserInfo(state, data) {
      state.userInfo = data
    },
    loginOut(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    },
    setPermsiions(state, data) {
      state.menus = data.menus
      state.points = data.points
    },
    removePermsisson(state) {
      state.menus = []
      state.points = []
    }
  },
  actions: {
    // 调用登录接口
    async loginUser(context, data) {
      const res = await login(data)
      context.commit('setToken', res.data.jwt)
      localStorage.setItem('loginTime', Date.now())
      resetRouter()
      router.push('/')
    },
    async getUser(context) {
      const result = await getUser()
      const permission = await getMmyPermissions()
      console.log(49, result, 50, permission)
      context.commit('setUserInfo', result.data)
      context.commit('setPermsiions', permission.data)
    },
    // 退出登录
    async loginOut(context) {
      context.commit('loginOut')
      context.commit('removeUserInfo')
      context.commit('removePermsisson')
    }
  }
}
